<template>
  <d2-container>
    <el-form :model="FormSearch" status-icon label-width="100px" class="demo-ruleForm">
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="条件查找" prop="good">
            <el-input
              type="text"
              v-model="FormSearch.good"
              placeholder="请输入单元名称"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-select v-model="typeId" @change="xqChange" placeholder="请选择小区">
            <el-option
              v-for="item in type"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="type1Id" placeholder="请选择楼栋">
            <el-option
              v-for="item in type1"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="searchClick()">查询</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <!-- 数据表格 -->
    <d2-crud
      ref="d2Crud"
      edit-title="编辑"
      add-title="添加单元信息"
      :columns="columns"
      :data="data"
      :rowHandle="rowHandle"
      :edit-template="editTemplate"
      :add-template="addTemplate"
      :add-rules="addRules"
      :form-options="formOptions"
      :pagination="page"
      :loading="loading"
      @dialog-open="handleDialogOpen"
      @row-edit="handleRowEdit"
      @row-add="handleRowAdd"
      @dialog-cancel="handleDialogCancel"
      @custom-emit-2="delGood"
      @pagination-current-change="paginationCurrentChange"
    >
    <el-button slot="header" style="margin-bottom: 5px;" @click="addRow">添加单元信息</el-button>
    </d2-crud>
  </d2-container>
</template>

<script>
import {
  getUptown,
  getUptownUnit,
  addUptownUnit,
  updateUptownUnit,
  getUptownBuilding,
  deleteUptownUnit,
} from "@/api/goods/index";
import util from "@/libs/util.js";

export default {
  data() {
    return {
      loading: false,
      // 搜索数据
      FormSearch: {
        good: ""
      },
      typeId: '',
      type: [],
      type1Id: '',
      type1: [],
      // 字段名称
      columns: [
        /* {
          title: "配置字母名称",
          key: "code",
          align: "center"
        }, */
        {
          title: "单元名称",
          key: "name",
          align: "center"
        },
      ],
      // 列表数据
      data: [],
      // 操作列数据
      rowHandle: {
        align: "center",
        width: 280,
        custom: [
          {
            text: "删除",
            type: "danger",
            size: "mini",
            emit: "custom-emit-2"
          },
        ],
        edit: {
          icon: "el-icon-edit",
          text: "编辑",
          size: "small"
        }
      },
      addTemplate: {
        housName: {
          title: "小区楼栋",
          value: "",
          component: {
            name: 'el-cascader',
            options: [],
            props:{
              lazy: true,
              lazyLoad (node, resolve) {
                const { level, value } = node;
                let params = {
                  page: 1,
                  limit: 9999999,
                  belongId: value
                };
                getUptownBuilding(params)
                  .then(res => {
                    if (res.success) {
                      let zopt = []
                        res.rows.map(item => {
                          let opt = {
                            value: item.id,
                            label: item.name,
                            leaf: level >= 1
                          }
                          zopt.push(opt)
                        })
                        resolve(zopt);
                    }
                  })
                  .catch(err => {
                    this.$message.error(err);
                  });
              }
            },
            span: 24,
            /* render: (h, params) => {
              return h(
                <el-select v-model='this.value1' placeholder="请选择">
                  <el-option
                    label="11"
                    value="ww">
                  </el-option>
                </el-select>
              )
            } */
          }
        },
        /* belongId: {
          title: "楼栋名称",
          value: "",
          component: {
            name: 'el-select',
            options: [],
            span: 24
          }
        }, */
        name: {
          title: "单元名称",
          value: ""
        },
      },
      addRules: {
        housName: [ { required: true, message: '请输入小区名称', trigger: 'blur' } ],
        // belongId: [ { required: true, message: '请输入楼栋名称', trigger: 'blur' } ],
        name: [ { required: true, message: '请输入单元名称', trigger: 'blur' } ],
      },
      editTemplate: {
        /* code: {
          title: "配置字母名称",
          value: ""
        }, */
        name: {
          title: "单元名称",
          value: ""
        },
      },
      formOptions: {
        labelWidth: "80px",
        labelPosition: "left",
        saveLoading: false
      },
      // 分页数据
      page: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      }
    };
  },
  created() {
    let params = {
      page: this.page.pageIndex,
      limit: this.page.pageSize
    };
    this.init(params);
  },
  mounted() {
    let params = {
      page: 1,
      limit: 9999999
    };
    getUptown(params)
      .then(res => {
        if (res.success) {
          let zopt = []
            res.rows.map(item => {
              let opt = {
                value: item.id,
                label: item.name
              }
              zopt.push(opt)
            })
            this.type = zopt
            this.addTemplate.housName.component.options = zopt
            this.type = zopt
        }
      })
      .catch(err => {
        this.$message.error(err);
      });
  },
  methods: {
    // 初始化身体数据列表
    init(params) {
      this.loading = true
      getUptownUnit(params)
        .then(res => {
          if (res.success) {
            this.data = res.rows;
            this.page.total = res.total;
          }
          this.loading = false
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err);
        });
    },

    // 小区选择改变楼栋
    xqChange(item) {
      console.log(item)
      let params = {
          page: 1,
          limit: 9999999,
          belongId: item
        };
      this.getBuild(params)
    },

    // 根据小区获取楼栋方法
    getBuild(params) {
      getUptownBuilding(params)
        .then(res => {
          if (res.success) {
            let zopt = []
              res.rows.map(item => {
                let opt = {
                  value: item.id,
                  label: item.name,
                }
                zopt.push(opt)
              })
              this.type1 = zopt;
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 普通的新增
    addRow() {
      this.$refs.d2Crud.showDialog({
        mode: "add"
      });
    },

    // 新增成功
    handleRowAdd(row, done) {
      this.formOptions.saveLoading = true;
      let params = {
        name: row.name,
        belongId: row.housName[1]
      };
      console.log(params)

      addUptownUnit(params)
        .then(res => {
          console.log(res);
          if (res.success) {
            this.$message({
              message: "添加成功",
              type: "success"
            });
          }

          // done可以传入一个对象来修改提交的某个字段
          done();
          // 保存按钮的loading状态
          this.formOptions.saveLoading = false;
          // 重新加载列表
          let params = {
            page: this.page.pageIndex,
            limit: this.page.pageSize,
          };
          this.init(params);
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 分页数改变，调用
    paginationCurrentChange(pageIndex) {
      let params = {
        limit: this.page.pageSize,
        name: this.FormSearch.good,
        belongId: this.type1Id
      };
      params.page = this.page.pageIndex = pageIndex;
      this.init(params);
    },

    // 条件查询搜索
    searchClick() {
      let params = {
        page: 1,
        limit: 10
      };
      params.name = this.FormSearch.good;
      params.belongId = this.type1Id;
      this.init(params);
    },

    // 重置查询
    resetForm() {
      this.FormSearch.good = "";
      let params = {
        page: 1,
        limit: 10
      };
      this.init(params);
    },

    // 点击编辑时 mode 为编辑或者添加，row为点击这一行数据
    handleDialogOpen({ mode, row }) {
      console.log(mode, row);
    },

    // 编辑提交
    handleRowEdit({ index, row }, done) {
      // 保存按钮的loading状态
      this.formOptions.saveLoading = true;
      let params = {};
      params.id = row.id;
      params.name = row.name;
      updateUptownUnit(params)
        .then(res => {
          if (res.success) {
            this.$message({
              message: "编辑成功",
              type: "success"
            });
          }
          // done可以传入一个对象来修改提交的某个字段
          done();
          // 保存按钮的loading状态
          this.formOptions.saveLoading = false;
          // 重新加载列表
          let params = {
            page: this.page.pageIndex,
            limit: this.page.pageSize
          };
          params.classLevel = 1;
          this.init(params);
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    // 取消编辑
    handleDialogCancel(done) {
      /* this.$message({
        message: "取消编辑",
        type: "warning"
      }); */
      done();
    },

    // 删除商品
    delGood({ index, row }) {
      let params = {
        id: row.id,
      }
      this.$confirm(`此操作将删除配置, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteUptownUnit(params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: "删除成功",
                  type: "success"
                });
                // 重新加载列表
                let params = {
                  page: this.page.pageIndex,
                  limit: this.page.pageSize,
                };
                this.init(params);
              }
            })
            .catch(err => {
              this.$message.error(err);
            });
        })
        .catch(err => {});
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
